'''
Created on 2013. 5. 13.

@author: Lee
'''

from google.appengine.api import channel
from google.appengine.ext import ndb
from kr.community.configure import JINJA_ENVIRONMENT
from kr.community.gaesessions import get_current_session
from kr.community.models import ChannelSession, ChatList
import json
import webapp2

class ChatPage(webapp2.RequestHandler):
    '''
        This is Chat Page.
        Summary of site contents.
    '''

    def get(self):
        session = get_current_session()
        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('chat.html')
        
        if session.is_active():
            user_key = ndb.Key(urlsafe=session['user'])
            user_entry = user_key.get()
            template_values['user'] = user_entry
            
            chat_token = channel.create_channel(session['user'])
            template_values['chat_token'] = chat_token
            template_values['chat_list'] = ChatList.query().order(-ChatList.timestamp).fetch(200)
            template_values['chat_list'].reverse()
            
            for chat_entry in template_values['chat_list']:
                start_idx = -1
                end_idx = -1
                http_flag = True
                try:
                    start_idx = chat_entry.msg.index("http")
                except ValueError:
                    try:
                        start_idx = chat_entry.msg.index("www")
                        http_flag = False   
                    except ValueError:
                        continue
                try:
                    end_idx = chat_entry.msg.index(" ", start_idx)
                except ValueError:
                    end_idx = len(chat_entry.msg)
                link = chat_entry.msg[start_idx:end_idx]
                if http_flag:
                    chat_entry.msg = chat_entry.msg.replace(link, "<a href='%s' target='_blank'>%s</a>"%(link, link))
                else:
                    chat_entry.msg = chat_entry.msg.replace(link, "<a href='http://%s' target='_blank'>%s</a>"%(link, link))
            template_values['user_list'] = ChannelSession.query()
            
        self.response.write(template.render(template_values))
            
class PostMsg(webapp2.RequestHandler):
    def get(self):
        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('result_msg.html')
        template_values['msg'] = "Wrong access"
        
        session = get_current_session()
        if session.is_active():
            user_key = ndb.Key(urlsafe=session['user'])
            user_entry = user_key.get()
            template_values['user'] = user_entry
        
        self.response.out.write(template.render(template_values))

    def post(self):
        session = get_current_session()        
        if session.is_active():
            user_key = ndb.Key(urlsafe=session['user'])
            user_entry = user_key.get()
            message = self.request.POST['msg']
            
            if message == "":
                self.response.write("Empty")
                return
            
            channel_msg = json.dumps({"success": True, "msg":message, "nick": user_entry.user_nickname})

            chat_msg = ChatList()
            chat_msg.msg = message
            chat_msg.user_nickname = user_entry.user_nickname
            chat_msg.put()
            channel_all = ChannelSession.query()
            for channel_entry in channel_all:            
                channel.send_message(channel_entry.session_id, channel_msg)        
            self.response.write("Success")
        else:
            self.redirect("/login/")
        
class Disconnected(webapp2.RequestHandler):
    def post(self):
        session_id   = self.request.get('from')
        channel_list = ChannelSession.query(ChannelSession.session_id==session_id)
        
        channel_all = ChannelSession.query()
        user_entry = ndb.Key(urlsafe=session_id).get()
        channel_msg = json.dumps({"success":True, "msg":"exit", "nick": user_entry.user_nickname, "token":session_id})
        for channel_entry in channel_all:                
            channel.send_message(channel_entry.session_id, channel_msg)
        if channel_list.count() != 0:
            for channel_entry in channel_list:
                channel_entry.key.delete()

class Connected(webapp2.RequestHandler):
    def post(self):
        session_id = self.request.get('from')
        user_entry = ndb.Key(urlsafe=session_id).get()
        channel_list = ChannelSession.query(ChannelSession.user_nickname==user_entry.user_nickname)
        if channel_list.count() == 0:
            channel_entry = ChannelSession()
            channel_entry.session_id = session_id
            channel_entry.user_nickname = user_entry.user_nickname
            channel_entry.put()
        else:
            for entry in channel_list:        
                entry.session_id = session_id
                entry.put()
            
        channel_all = ChannelSession.query()
        channel_msg = json.dumps({"success":True, "msg":"join", "nick": user_entry.user_nickname, "token":session_id})
        for channel_loop in channel_all:
            channel.send_message(channel_loop.session_id, channel_msg)
